#include <functional>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
using namespace std;

namespace ThreadModule
{
    using func_t = std::function<void()>;
    static int number = 1;
    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };

    class Thread
    {
    private:
        // 成员方法！ 这里不用stastic的话 Routine就是成员方法 参数默认含有this指针 不匹配线程调用时的参数
        static void *Routine(void *args)
        {
            Thread * td = static_cast<Thread*>(args);
            td->_status=TSTATUS::RUNNING;
            td->_func();
            
            return nullptr;
        }
        void EnableDetach() {_joinable = false;}

    public:
        Thread(func_t func) : _func(func), _status(TSTATUS::NEW), _joinable(true)
        {
            _name = "pthread-"+std::to_string(number++);
            _pid = getpid();
        }
        // 创建线程
        bool Start()
        {
            if (_status != TSTATUS::RUNNING)
            {
                int n = pthread_create(&_tid, nullptr, Routine, (void *)this);
                if (n != 0)
                {
                    cout << "pthread create fail" << endl;
                    return false;
                }
               
                return true;
            }
            return false;
        }
        bool Stop()
        {
             if(_status == TSTATUS::RUNNING)
             {
                int n= pthread_cancel(_tid);
                if(n!=0)
                {
                    cout<<"stop pthread fail"<<endl;
                    return false;
                }
                _status = TSTATUS::STOP;
                return true;
             }
             return false;
        }
        bool Join()
        {
            if(_joinable)
             {
                
                int n= pthread_join(_tid,nullptr);
                if(n!=0)
                {
                    cout<<"join pthread fail"<<endl;
                    return false;
                }
                _status=TSTATUS::STOP;
                return true;
             }
             return false;
        }
        void Detach()
        {
            EnableDetach();
            pthread_detach(_tid);
        }
        bool IsJoinable() {return _joinable;}
        std::string Name() {return _name;}
        pid_t Getpid() {return _pid;}
        pthread_t gettid() {return _tid;}
        
         
        ~Thread()
        {

        }

    private:
        std::string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable; // 是否是分离的，默认不是
        func_t _func;
        TSTATUS _status;
    };
}